#!/usr/bin/perl -w
package DicerCant::World;
# DicerCant::World.pm:
#   This package is for working with DicerCant .map and related files.
#
# Copyright (C) 2009  Justin Lee  < kool.name at gmail.com >
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
# USA.


use strict;
use warnings;

use DicerCant::World::Tile;


# Globals:



# Methods:

sub new {
	shift->spawn(@_)
}

sub spawn {
	shift->parse(shift)->build(@_)
}

sub build {
	my ($map) = splice(@_, 0, 1);

	my @sets = map {
		ref($_) # it's ambiguous without (), might as well add $_
			? $_
			: (DicerCant::World::Tile->build($_) or
				(warn("Unable to build $_"), return (undef)))
	} @_;

	for (my $r = @{$map}; $r--; ) {
		for (my $c = @{$map->[$r]}; $c--; ) {
			foreach my $set (@sets) {
				my $t = $set->get($map->[$r][$c]);

				defined($t) and do {
					$map->[$r][$c] = $t;
					last;
				};
			}
			ref($map->[$r][$c]) or do {
				warn(
					sprintf(
						'Unknown tile at (%d, %d)',
						$r + 1,
						$c + 1
					)
				), return (undef);
			};
		}
	}

	return ($map);
}

sub parse {
	my ($package, $file) = @_;

	open(my $map, '<', $file) or do {
		warn("$!: $file"), return (undef);
	};

	return (
		bless (
			[
				map {
					chomp; [ split // ] # google code's perl parser sucks
				} <$map>
			],

			$package,
		)
	);
}


__PACKAGE__;

